package com.atguigu.flink.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/13 10:05
 */
public class Flink03_UnBounded_WC_Lamda {
    public static void main(String[] args) throws Exception {
        System.out.println("Flink03_UnBounded_WC_Lambda.main");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        env.disableOperatorChaining();

        // 从数据源读取数据
        env
            .socketTextStream("hadoop162", 9999)
            .flatMap(new FlatMapFunction<String, String>() {
                @Override
                public void flatMap(String line,
                                    Collector<String> out) throws Exception {
                    for (String word : line.split(" ")) {
                        out.collect(word);
                    }
                }
            })
            .map(new MapFunction<String, Tuple2<String, Long>>() {
                @Override
                public Tuple2<String, Long> map(String word) throws Exception {
                    return Tuple2.of(word, 1L);
                }
            })
            .filter(x -> true)
            .keyBy(new KeySelector<Tuple2<String, Long>, String>() {
                @Override
                public String getKey(Tuple2<String, Long> t) throws Exception {
                    return t.f0;
                }
            })
            .sum(1)
            .print();
        
        // 执行流环境
        env.execute();
    }
}

/*
1. 函数式接口
    如果一个接口只有一个抽象方法
    
    传递函数式接口对象的时候, 可以使用lambda表示
    
    a -> ...
    
    


2. 方法引用

 */